package com.googlecode.agscrum.model.entity;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Transient;

import org.hibernate.validator.Email;
import org.hibernate.validator.NotEmpty;
import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.beans.factory.annotation.Configurable;

import com.googlecode.agscrum.model.exceptions.GScrumDomainException;
import com.googlecode.agscrum.model.exceptions.MessageFactory;
import com.googlecode.agscrum.model.exceptions.GScrumDomainException.TypeMessage;
import com.googlecode.agscrum.model.validator.annotation.NotNull;
import com.googlecode.agscrum.model.validator.annotation.Validate;

@Entity
@SequenceGenerator(name = "user_sequence", sequenceName = "user_sequence")
@NamedQueries(value = {
		@NamedQuery(name = "User.findByLogin", query = "from User u"),
		@NamedQuery(name = "User.searchQuery", query = "select new User(u.id, u.name, u.login,u.email) from User u"),
		@NamedQuery(name = "User.duplicateValidate", query = "select count(*) as total from User u where lower(u.login)=lower(:login)") })
@Configurable(autowire = Autowire.BY_NAME)
@Table(name = "USERS")
public class User {
	@Id
	@GeneratedValue(generator = "user_sequence", strategy = GenerationType.SEQUENCE)
	@Column(name = "id_user")
	private Long id;
	@Column(length = 80, nullable = false)
	@NotNull(message = "user.name.required")
	@NotEmpty(message = "user.name.required")
	private String name;
	@Column(length = 80, nullable = false)
	@NotNull(message = "user.email.required")
	@NotEmpty(message = "user.email.required")
	@Email(message = "user.email.invalid")
	private String email;
	@Column(length = 12, nullable = false, name = "USERNAME")
	@NotNull(message = "user.login.required")
	@NotEmpty(message = "user.login.required")
	private String login;
	@Column(length = 40, nullable = false, name = "PASSWORD")
	@NotNull(message = "user.password.required")
	@NotEmpty(message = "user.password.required")
	private String password;

	@Column(name = "ENABLED", nullable = false)
	private boolean enabled = true;

	@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
	@JoinColumn(name = "id_user")
	private List<PermissionProject> permissions;

	public User() {
	}

	public User(Long id, String name, String email, String login) {
		super();
		this.id = id;
		this.name = name;
		this.email = email;
		this.login = login;
	}

	@Transient
	private MessageFactory messageFactory;

	public void setMessageFactory(MessageFactory messageFactory) {
		this.messageFactory = messageFactory;
	}

	@Validate
	@SuppressWarnings("all")
	public void changePassword(@NotNull String oldPassword,
			@NotNull String newPassword, @NotNull String repeatPassword) {
		if (oldPassword.equals(this.password)) {
			if (newPassword.equals(repeatPassword)) {
				this.password = newPassword;
			} else {
				throw new GScrumDomainException(messageFactory.createMessage(
						"user.different.new.passwords", null,
						TypeMessage.ERROR, null));
			}
		} else {
			throw new GScrumDomainException(messageFactory.createMessage(
					"user.different.passwords", null, TypeMessage.ERROR, null));
		}
	}

	public void addRolePermission(Product product, Role role) {
		if (permissions == null) {
			permissions = new ArrayList<PermissionProject>();
		}
		PermissionProject permissionProject = new PermissionProject();
		permissionProject.setProduct(product);
		permissionProject.setUser(this);
		if (permissions.contains(permissionProject)) {
			permissionProject = permissions.get(permissions
					.indexOf(permissionProject));
		} else {
			permissions.add(permissionProject);
		}
		permissionProject.addRole(role);
	}

	public void removeRolePermission(Product product, Role role) {
		PermissionProject permissionProject = new PermissionProject();
		permissionProject.setProduct(product);
		permissionProject.setUser(this);
		if (permissions.contains(permissionProject)) {
			permissionProject = permissions.get(permissions
					.indexOf(permissionProject));
			permissionProject.removeRole(role);
			if (permissionProject.getTotalRoles() == 0) {
				permissions.remove(permissionProject);
			}
		}
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		result = prime * result + ((login == null) ? 0 : login.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		User other = (User) obj;
		if (id == null) {
			if (other.id != null)
				return false;
		} else if (!id.equals(other.id))
			return false;
		if (login == null) {
			if (other.login != null)
				return false;
		} else if (!login.equals(other.login))
			return false;
		return true;
	}

	public String getLogin() {
		return login;
	}

	public String getPassword() {
		return password;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public void setLogin(String login) {
		this.login = login;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public boolean isEnabled() {
		return enabled;
	}

	public void setEnabled(boolean enabled) {
		this.enabled = enabled;
	}
	
	
}
